package edu.sctu.lab03;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2018-6-11.
 */
public class IPFilter implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        String ip = servletRequest.getRemoteAddr();
        System.out.println(ip);

        if (ip.equals(this.filterConfig.getInitParameter("ip"))) {

            servletResponse.setCharacterEncoding("gbk");
            PrintWriter out = servletResponse.getWriter();
            out.write("IP地址被禁止访问！");

        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
